package com.pmcc.platform.shop.service;


import com.alibaba.fastjson.JSONObject;
import com.pmcc.platform.giftGoods.entity.Goods;
import com.pmcc.platform.giftGoods.repository.GoodsRepository;
import com.pmcc.platform.giftGoods.vo.GoodsVo;
import com.pmcc.platform.salesman.entity.Salesman;
import com.pmcc.platform.salesman.repository.SalesmanRepository;
import com.pmcc.platform.shop.vo.ShopDetailVo;
import com.pmcc.platform.shop.vo.ShopDetailsVo;
import com.pmcc.platform.shopping.entity.GoodsGift;
import com.pmcc.platform.shopping.entity.Shopping;
import com.pmcc.platform.shopping.entity.ShopLibory;
import com.pmcc.platform.shopping.entity.ShoppingGiftChangeLog;
import com.pmcc.platform.shopping.enums.GiftChange;
import com.pmcc.platform.shopping.repository.GoodsGiftRepository;
import com.pmcc.platform.shopping.repository.ShopLiboryRepository;
import com.pmcc.platform.shopping.repository.ShoppingGiftChangeLogRepository;
import com.pmcc.platform.shopping.repository.ShoppingRepository;
import com.pmcc.platform.shop.entity.ShopInfo;
import com.pmcc.platform.shop.repository.ShopInfoRepository;
import com.pmcc.platform.shop.vo.AddressVo;
import com.pmcc.platform.shopping.vo.HistoryUserLogVo;
import com.pmcc.platform.user.entity.MinShoppingUserInfo;
import com.pmcc.platform.user.entity.UserInfo;
import com.pmcc.platform.user.repository.MinShoppingUserInfoRepository;
import com.pmcc.platform.user.repository.UserInfoRepository;
import com.pmcc.utils.AntPage;
import com.pmcc.utils.ApiResultBean;
import com.pmcc.utils.StringUtil;
import com.pmcc.utils.wechat.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class ShopInfoService {

    @Autowired
    ShopInfoRepository shopInfoRepository;

    @Autowired
    ShoppingRepository shoppingRepository;

    @Autowired
    GoodsGiftRepository goodsGiftRepository;

    @Autowired
    ShopLiboryRepository shopLiboryRepository;

    @Autowired
    SalesmanRepository salesmanRepository;

    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    ShoppingGiftChangeLogRepository shoppingGiftChangeLogRepository;

    @Autowired
    UserInfoRepository userInfoRepository;

    @Autowired
    MinShoppingUserInfoRepository minShoppingUserInfoRepository;


    @Value("${baiduApi.key}")
    private String key;


    public ApiResultBean queryAllShop(AntPage antPage, String name, String bossName, String provinces, String city, String area) {
        ApiResultBean apiResultBean = new ApiResultBean();
        Page<ShopInfo> shopInfos = shopInfoRepository.findAllByDelFlagAndNameContainsAndBossNameContainsAndProvincesContainsAndCityContainsAndAreaContainsOrderByCreateTimeDesc("0", name, bossName, provinces, city, area, antPage.getPageRequest());

        for (ShopInfo shopInfo : shopInfos) {

            List<ShopLibory> shopLiborys = shopLiboryRepository.findAllByShopIdAndDelFlag(shopInfo.getId(), "0");
            int giftNum = 0;
            int residueNum = 0;
            if (shopLiborys.size() > 0) {
                for (ShopLibory shopLibory : shopLiborys) {
                    giftNum = giftNum + shopLibory.getGoodsNum();
                    residueNum = residueNum + shopLibory.getTotalNum();
                }
            }
            shopInfo.setGiftNum(giftNum);
            shopInfo.setResidueNum(residueNum);

            List<Shopping> shoppings = shoppingRepository.findAllByShopIdAndDelFlag(shopInfo.getId(), "0");
            shopInfo.setShoppingNum(shoppings.size());

            Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
            shopInfo.setSalesmanName(salesman.getName());
            shopInfo.setSalesmanPhone(salesman.getPhone());
            //查出发送放赠品数量
            int getNum = goodsGiftRepository.countShopNum(shopInfo.getId(), "1", "0");
            shopInfo.setGetNum(getNum);


        }
        apiResultBean.setData(shopInfos, antPage);
        apiResultBean.setMsg("查询成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }


    public ApiResultBean queryShop(String shopId) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if (StringUtil.isEmpty(shopId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("id为空");
            return apiResultBean;
        }
        //当前店铺信息
        ShopInfo shopInfo = shopInfoRepository.findAllByDelFlagAndId("0", shopId);

        Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
        shopInfo.setSalesmanName(salesman.getName());
        shopInfo.setSalesmanPhone(salesman.getPhone());

        //查出发送放赠品数量
        int getNum = goodsGiftRepository.countShopNum(shopInfo.getId(), "1", "0");
        shopInfo.setGetNum(getNum);

        List<ShopLibory> shoppingLibories = shopLiboryRepository.findAllByShopIdAndDelFlag(shopInfo.getId(), "0");

        int residueNum = 0;
        for (ShopLibory shoppingLibory : shoppingLibories) {

            residueNum = residueNum + shoppingLibory.getGoodsNum();
        }

        shopInfo.setResidueNum(residueNum);
        shopInfo.setResidueNum(residueNum);


        apiResultBean.setData(shopInfo);
        apiResultBean.setMsg("查询成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean modifyShop(ShopInfo shopInfo) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopInfo.getId())) {
            apiResultBean.setMsg("id不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        ShopInfo shopInfo1 = shopInfoRepository.findOne(shopInfo.getId());

        if (StringUtil.isNotEmpty(shopInfo.getName())) {
            shopInfo1.setName(shopInfo.getName());
        }
        if (StringUtil.isNotEmpty(shopInfo.getImagePath())) {
            shopInfo1.setImagePath(shopInfo.getImagePath());
        }

        if (StringUtil.isNotEmpty(shopInfo.getOperatingStatus())) {
            shopInfo1.setOperatingStatus(shopInfo.getOperatingStatus());
        }
        if (StringUtil.isNotEmpty(shopInfo.getShopStatus())) {
            shopInfo1.setShopStatus(shopInfo.getShopStatus());
        }
        if (StringUtil.isNotEmpty(shopInfo.getDetailedAddress())) {
            shopInfo1.setDetailedAddress(shopInfo.getDetailedAddress());
        }


        shopInfoRepository.save(shopInfo1);
        apiResultBean.setMsg("修改成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }


    public ApiResultBean deletShop(String shopId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("店铺id不能为空");
            return apiResultBean;
        }
        ShopInfo shopInfo = shopInfoRepository.findOne(shopId);
        shopInfo.setDelFlag("1");
        apiResultBean.setMsg("删除成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }


    public ApiResultBean salesmaneletShop(String shopId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("店铺id不能为空");
            return apiResultBean;
        }
        ShopInfo shopInfo = shopInfoRepository.findOne(shopId);
        shopInfo.setDelFlag("1");
        apiResultBean.setMsg("删除成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean addShop(ShopInfo shopInfo) {
        ApiResultBean apiResultBean = new ApiResultBean();
        Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
        if (salesman == null) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("业务员不存在");
            return apiResultBean;
        }
        if (shopInfo == null) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("传入的为空");
            return apiResultBean;
        }
        ShopInfo shopInfo1 = new ShopInfo();
        if (StringUtil.isEmpty(shopInfo.getLatitude().toString()) && StringUtil.isEmpty(shopInfo.getLongitude().toString())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("传入的经纬度为空");
            return apiResultBean;
        }
        String prapeze = shopInfo.getLatitude() + "," + shopInfo.getLongitude();
        AddressVo addressVo = new AddressVo();
        try {
            addressVo = gain(prapeze);
        } catch (Exception e) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("api接口错误");
            return apiResultBean;
        }
        shopInfo1.setName(shopInfo.getName());
        shopInfo1.setImagePath(shopInfo.getImagePath());

        shopInfo1.setLatitude(shopInfo.getLatitude());
        shopInfo1.setLongitude(shopInfo.getLongitude());
        shopInfo1.setDetailedAddress(shopInfo.getDetailedAddress());
        shopInfo1.setBossName(shopInfo.getBossName());
        shopInfo1.setPhone(shopInfo.getPhone());
        shopInfo1.setSalesmanId(shopInfo.getSalesmanId());
        shopInfo1.setAddress(addressVo.getAddress());
        shopInfo1.setProvinces(addressVo.getProvince());
        shopInfo1.setCity(addressVo.getCity());
        shopInfo1.setAreaCode(addressVo.getAdcode());
        shopInfo1.setArea(addressVo.getDistrict());

        shopInfo1.setOperatingStatus("1");
        shopInfo1.setShopStatus("1");
        shopInfoRepository.save(shopInfo1);
        apiResultBean.setMsg("添加店铺成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }


    public ApiResultBean salesamanAddShop(ShopInfo shopInfo) {
        ApiResultBean apiResultBean = new ApiResultBean();
        Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
        if (salesman == null) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("业务员不存在");
            return apiResultBean;
        }
        if (shopInfo == null) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("传入的为空");
            return apiResultBean;
        }
        ShopInfo shopInfo1 = new ShopInfo();
        if (StringUtil.isEmpty(shopInfo.getLatitude().toString()) && StringUtil.isEmpty(shopInfo.getLongitude().toString())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("传入的经纬度为空");
            return apiResultBean;
        }
        String prapeze = shopInfo.getLatitude() + "," + shopInfo.getLongitude();
        AddressVo addressVo = new AddressVo();
        try {
            addressVo = gain(prapeze);
        } catch (Exception e) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("api接口错误");
            return apiResultBean;
        }
        shopInfo1.setName(shopInfo.getName());
        shopInfo1.setImagePath(shopInfo.getImagePath());
        shopInfo1.setLatitude(shopInfo.getLatitude());
        shopInfo1.setLongitude(shopInfo.getLongitude());
        shopInfo1.setDetailedAddress(shopInfo.getDetailedAddress());
        shopInfo1.setBossName(shopInfo.getBossName());
        shopInfo1.setPhone(shopInfo.getPhone());
        shopInfo1.setSalesmanId(shopInfo.getSalesmanId());
        shopInfo1.setAddress(addressVo.getAddress());
        shopInfo1.setProvinces(addressVo.getProvince());
        shopInfo1.setCity(addressVo.getCity());
        shopInfo1.setAreaCode(addressVo.getAdcode());
        shopInfo1.setArea(addressVo.getDistrict());
        shopInfo1.setOperatingStatus("1");
        shopInfo1.setShopStatus("1");
        shopInfoRepository.save(shopInfo1);
        apiResultBean.setMsg("添加店铺成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public AddressVo gain(String prapeze) {

        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + key + "&output=json&coordtype=wgs84ll&location=" + prapeze;
        String f = HttpClientUtil.httpGetRequest(url);
        JSONObject jsonObject = JSONObject.parseObject(f);
        String result = jsonObject.get("result").toString();
        JSONObject jsonObjects = JSONObject.parseObject(result);
        String address = jsonObjects.getString("formatted_address");
        String addressComponent = jsonObjects.getString("addressComponent");
        JSONObject jsonObject1 = JSONObject.parseObject(addressComponent);
        String province = jsonObject1.getString("province");
        String city = jsonObject1.getString("city");
        String district = jsonObject1.getString("district");
        String adcode = jsonObject1.getString("adcode");
        AddressVo addressVo = new AddressVo();
        addressVo.setAddress(address);
        addressVo.setCity(city);
        addressVo.setDistrict(district);
        addressVo.setAdcode(adcode);
        addressVo.setProvince(province);
        return addressVo;
    }


    public ApiResultBean queryshoping(String shopId, AntPage antPage) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopId)) {
            apiResultBean.setMsg("店铺id不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        Page<Shopping> shoppings = shoppingRepository.findAllByShopIdAndDelFlag(shopId, "0", antPage.getPageRequest());
        if (shoppings.getSize() > 0) {
            apiResultBean.setCode(ApiResultBean.SUCCESS);
            apiResultBean.setData(shoppings, antPage);
            apiResultBean.setMsg("查询成功");
        }
        return apiResultBean;
    }

    public ApiResultBean selectShop(String salesmanId, AntPage antPage, String field) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(salesmanId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("参数为空");
            return apiResultBean;
        }
        Page<ShopInfo> shopInfos = shopInfoRepository.findAllBySalesmanIdAndDelFlagAndNameContaining(salesmanId, "0", field, antPage.getPageRequest());
        Page<ShopInfo> shopInfos1=shopInfoRepository.findAllBySalesmanIdAndDelFlagAndPhoneContains(salesmanId, "0", field, antPage.getPageRequest());
        List<ShopInfo> shopInfos2=new ArrayList<>();

        if(shopInfos.getSize()>0){
            for (ShopInfo shopInfo: shopInfos ) {
                shopInfos2.add(shopInfo);
            }
        }
        if(shopInfos1.getSize()>0){
            for (ShopInfo shopInfo: shopInfos1 ) {
                shopInfos2.add(shopInfo);
            }
        }

        Set<ShopInfo> ts = new HashSet<ShopInfo>();
        ts.addAll(shopInfos2);
        List<ShopInfo> shopInfos3=new ArrayList<ShopInfo>();
        shopInfos3.addAll(ts);

        apiResultBean.setData(shopInfos3, antPage,shopInfos.getTotalElements()+shopInfos1.getTotalElements());
        apiResultBean.setMsg("查询成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean goodsList(String salesmanId, AntPage antPage, String goodsName) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(salesmanId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("参数为空");
            return apiResultBean;
        }
        Page<Goods> goodsPage = goodsRepository.findAllByNameContainsAndDelFlag(goodsName, "0", antPage.getPageRequest());
        List<GoodsVo> goodsVos = new ArrayList<>();
        if (goodsPage.getSize() > 0) {
            for (Goods goods : goodsPage) {
                GoodsVo goodsVo = new GoodsVo();
                goodsVo.setImages(goods.getImages());
                goodsVo.setName(goods.getName());
                goodsVo.setGoodsId(goods.getId());
                int s1 = goodsGiftRepository.countAllBySalesmanIdAndDelFlagAndStateAndGoodsId(salesmanId, "0", "1", goods.getId());
                goodsVo.setGetNum(s1);
                //找出业务员的所有分配记录
                List<ShoppingGiftChangeLog> logs = shoppingGiftChangeLogRepository.findAllBySalesmanIdAndDelFlagAndGiftChangeAndGooodId(salesmanId, "0", GiftChange.ALLOCATION,goods.getId());
                int s2 = 0;
                if (logs.size() > 0) {
                    for (ShoppingGiftChangeLog shoppingGiftChangeLog : logs) {
                        s2 = s2 + shoppingGiftChangeLog.getChangeNum();
                    }

                }
                //找出业务员所有的收回记录
                List<ShoppingGiftChangeLog> logs1 = shoppingGiftChangeLogRepository.findAllBySalesmanIdAndDelFlagAndGiftChangeAndGooodId(salesmanId, "0", GiftChange.WITHDRAW,goods.getId());
                int s3 = 0;
                if (logs1.size() > 0) {
                    for (ShoppingGiftChangeLog shoppingGiftChangeLog : logs1) {
                        s3 = s3 + shoppingGiftChangeLog.getChangeNum();
                    }

                }
                if(s2>s3){
                    goodsVo.setSendNum(s2-s3);
                }
                goodsVos.add(goodsVo);
            }
        }
       apiResultBean.setMsg("查询成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setData(goodsVos,antPage,goodsPage.getTotalElements());
        return apiResultBean;
    }

    public ApiResultBean getDetail(String salesmanId,String goodsId,AntPage antPage){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)|| StringUtil.isEmpty(goodsId)){
            apiResultBean.setMsg("参数为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        Page<GoodsGift> goodsGifts=goodsGiftRepository.findAllBySalesmanIdAndGoodsIdAndStateAndDelFlagOrderByCreateTimeDesc(salesmanId,goodsId,"1","0",antPage.getPageRequest());
       List<HistoryUserLogVo> historyUserLogVos=new ArrayList<>();
        if(goodsGifts.getSize()>0){
            for (GoodsGift goodsGift:goodsGifts ) {
                HistoryUserLogVo historyUserLogVo=new HistoryUserLogVo();
                List<UserInfo> userInfos=userInfoRepository.findAllByOppenIdAndDelFlag(goodsGift.getUserOpenId(),"0");
                historyUserLogVo.setGetTime(goodsGift.getModifyTime());
                if(userInfos.size()>0){
                    historyUserLogVo.setNikName(userInfos.get(0).getNickname());
                    historyUserLogVo.setImages(userInfos.get(0).getHeadimgurl());
                }
                historyUserLogVos.add(historyUserLogVo);
            }
        }
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("成功");
        apiResultBean.setData(historyUserLogVos,antPage,goodsGifts.getTotalElements());
        return  apiResultBean;
    }

    public ApiResultBean shopsList(String shopId,AntPage antPage){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(shopId)){
            apiResultBean.setMsg("参数不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        Page<Shopping> shoppings=shoppingRepository.findAllByShopIdAndDelFlag(shopId,"0",antPage.getPageRequest());
        if(shoppings.getSize()>0){
            for (Shopping shopping: shoppings ) {
                MinShoppingUserInfo minShoppingUserInfo=minShoppingUserInfoRepository.findAllByIdAndDelFlag(shopping.getMiniUserId(),"0");
               if(minShoppingUserInfo!=null){
                   shopping.setImage(minShoppingUserInfo.getPhotoUrl());
               }

            }
        }
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("成功");
        apiResultBean.setData(shoppings,antPage);
        return  apiResultBean;
    }

    public  ApiResultBean shopDetail(String shopId,String startTime,String endTime,AntPage antPage){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(shopId)){
            apiResultBean.setMsg("参数为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        Page<ShopLibory> shopLibories=null;
        if(StringUtil.isEmpty(endTime)||StringUtil.isEmpty(startTime)){
            shopLibories=shopLiboryRepository.findAllByShopIdAndDelFlag(shopId,"0",antPage.getPageRequest());
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start = null;
            Date end = null;
            try {
                start = sdf.parse(startTime);
                end = sdf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            shopLibories=shopLiboryRepository.findAllByShopIdAndDelFlagAndCreateTimeBetween(shopId,"0",start,end,antPage.getPageRequest());
        }

        HashMap<String,ShopInfo> hashMap=new HashMap<>();
        ShopInfo shopInfo=shopInfoRepository.findAllByDelFlagAndId("0",shopId);
        hashMap.put("shopinfo",shopInfo);

        List<ShopDetailsVo> shopDetailsVos=new ArrayList<>();
        if(shopLibories.getSize()>0){
            for (ShopLibory shopLibory:shopLibories ) {
                ShopDetailsVo shopDetailsVo=new ShopDetailsVo();
                Goods goods=goodsRepository.findAllByIdAndDelFlag(shopLibory.getGoodsId(),"0");
                shopDetailsVo.setGoodsImage(goods.getImages());
                shopDetailsVo.setGoodsName(goods.getName());
                shopDetailsVo.setNums(shopLibory.getGoodsNum());
                int a=goodsGiftRepository.countshopandgoodNum(shopId,goods.getId(),"1","0");
                shopDetailsVo.setGetNums(a);
                shopDetailsVo.setGoodsId(goods.getId());
                List<ShopDetailVo> shopDetailVos=new ArrayList<>();
                List<String > strings=goodsGiftRepository.findAllDistinctByUShoppingId("1","0",shopId,goods.getId());
                if(strings.size()>0){
                    for (String str:strings ) {
                        ShopDetailVo shopDetailVo=new ShopDetailVo();
                        Shopping shopping=shoppingRepository.findAllByIdAndDelFlag(str,"0");
                        int b=goodsGiftRepository.countAllByShoppingIdAndDelFlagAndStateAndGoodsId(str,"0","1",goods.getId());
                        shopDetailVo.setGetNum(b);
                        shopDetailVo.setIsPerpetual(shopping.getIsPerpetual());
                        shopDetailVo.setShoppingName(shopping.getName());
                        shopDetailVos.add(shopDetailVo);
                    }
                }
                shopDetailsVo.setShopDetailVos(shopDetailVos);
                shopDetailsVos.add(shopDetailsVo);
            }

        }
        apiResultBean.setData(shopInfo);
        apiResultBean.setData(shopDetailsVos,antPage,shopLibories.getTotalElements());
        apiResultBean.setMsg("成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return  apiResultBean;
    }

    public  ApiResultBean addGoodsGift(String shopId,String goodsId,int num,String salesmanId){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(shopId)|| StringUtil.isEmpty(goodsId)){
            apiResultBean.setMsg("参数不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        List<ShopLibory> shopLibories=shopLiboryRepository.findAllByShopIdAndGoodsIdAndDelFlag(shopId,goodsId,"0");


        ShoppingGiftChangeLog shoppingGiftChangeLog=new ShoppingGiftChangeLog();
        shoppingGiftChangeLog.setChangeNum(num);
        shoppingGiftChangeLog.setSalesmanId(salesmanId);
        shoppingGiftChangeLog.setGiftChange(GiftChange.ALLOCATION);
        shoppingGiftChangeLog.setShopId(shopId);
        shoppingGiftChangeLog.setGooodId(goodsId);
        shoppingGiftChangeLogRepository.save(shoppingGiftChangeLog);
        if(shopLibories.size()>0){
            if(StringUtil.isEmpty(String.valueOf(shopLibories.get(0).getGoodsNum()))){
                shopLibories.get(0).setGoodsNum(shopLibories.get(0).getGoodsNum()+num);
                shopLibories.get(0).setTotalNum(shopLibories.get(0).getTotalNum()+num);
                shopLiboryRepository.save( shopLibories.get(0));



            }

        }else {
            Goods goods=goodsRepository.findAllByIdAndDelFlag(goodsId,"0");
            ShopLibory shopLibory=new ShopLibory();
            shopLibory.setGoodsNum(num);
            shopLibory.setGoodsId(goodsId);
            shopLibory.setShopId(shopId);
            shopLibory.setThreshold(goods.getThreshold());
            shopLibory.setTotalNum(num);
            shopLiboryRepository.save(shopLibory);

        }
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("添加成功");
        return  apiResultBean;
    }

    public ApiResultBean modifyGoodsGiftNum(String shopId,String goodsId,int num,String state,String salesmanId){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(shopId)||StringUtil.isEmpty(goodsId)){
            apiResultBean.setMsg("参数不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }
        List<ShopLibory> shopLibories=shopLiboryRepository.findAllByShopIdAndGoodsIdAndDelFlag(shopId,goodsId,"0");
        //减少
        if(state.equals("1")){
            if(shopLibories.size()>0){
                if(num>shopLibories.get(0).getGoodsNum()){
                    apiResultBean.setMsg("当前库存不足");
                    apiResultBean.setCode(ApiResultBean.FAIL);
                    return  apiResultBean;
                }

               shopLibories.get(0).setGoodsNum(shopLibories.get(0).getGoodsNum()-num);
                shopLibories.get(0).setTotalNum(shopLibories.get(0).getTotalNum()-num);
                shopLiboryRepository.save(shopLibories.get(0));

                ShoppingGiftChangeLog shoppingGiftChangeLog=new ShoppingGiftChangeLog();
                shoppingGiftChangeLog.setChangeNum(num);
                shoppingGiftChangeLog.setSalesmanId(salesmanId);
                shoppingGiftChangeLog.setGiftChange(GiftChange.WITHDRAW);
                shoppingGiftChangeLog.setShopId(shopId);
                shoppingGiftChangeLog.setGooodId(goodsId);
                shoppingGiftChangeLogRepository.save(shoppingGiftChangeLog);
            }

        }else {
            if(shopLibories.size()>0){

                shopLibories.get(0).setGoodsNum(shopLibories.get(0).getGoodsNum()+num);
                shopLibories.get(0).setTotalNum(shopLibories.get(0).getTotalNum()+num);
                shopLibories.get(0).setTotalNum(shopLibories.get(0).getTotalNum()+num);
                shopLiboryRepository.save(shopLibories.get(0));

                ShoppingGiftChangeLog shoppingGiftChangeLog=new ShoppingGiftChangeLog();
                shoppingGiftChangeLog.setChangeNum(num);
                shoppingGiftChangeLog.setSalesmanId(salesmanId);
                shoppingGiftChangeLog.setGiftChange(GiftChange.ALLOCATION);
                shoppingGiftChangeLog.setShopId(shopId);
                shoppingGiftChangeLog.setGooodId(goodsId);
                shoppingGiftChangeLogRepository.save(shoppingGiftChangeLog);

            }


        }
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("改动成功");
        return  apiResultBean;
    }
    public ApiResultBean salesmanModifyShop(ShopInfo shopInfo){
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopInfo.getId())) {
            apiResultBean.setMsg("id不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        ShopInfo shopInfo1 = shopInfoRepository.findOne(shopInfo.getId());

        if (StringUtil.isNotEmpty(shopInfo.getName())) {
            shopInfo1.setName(shopInfo.getName());
        }
        if (StringUtil.isNotEmpty(shopInfo.getImagePath())) {
            shopInfo1.setImagePath(shopInfo.getImagePath());
        }

        if (StringUtil.isNotEmpty(shopInfo.getOperatingStatus())) {
            shopInfo1.setOperatingStatus(shopInfo.getOperatingStatus());
        }
        if (StringUtil.isNotEmpty(shopInfo.getShopStatus())) {
            shopInfo1.setShopStatus(shopInfo.getShopStatus());
        }
        if (StringUtil.isNotEmpty(shopInfo.getDetailedAddress())) {
            shopInfo1.setDetailedAddress(shopInfo.getDetailedAddress());
        }

        if (StringUtil.isNotEmpty(shopInfo.getBossName())) {
            shopInfo1.setBossName(shopInfo.getBossName());
        }

        if (StringUtil.isNotEmpty(shopInfo.getPhone())) {
            shopInfo1.setPhone(shopInfo.getPhone());
        }


        shopInfoRepository.save(shopInfo1);
        apiResultBean.setMsg("修改成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean querySalesmanIdAllShopping(String shopId, AntPage antPage) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopId)) {
            apiResultBean.setMsg("店铺id不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        Page<Shopping> shoppings = shoppingRepository.findAllByShopIdAndDelFlag(shopId, "0", antPage.getPageRequest());
        if (shoppings.getSize() > 0) {
            apiResultBean.setCode(ApiResultBean.SUCCESS);
            apiResultBean.setData(shoppings, antPage);
            apiResultBean.setMsg("查询成功");
        }
        return apiResultBean;
    }

    public ApiResultBean shoppingDeatil(String shoppingId,String startTime,String endTime,AntPage antPage,String shopId){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(shoppingId)){
            apiResultBean.setMsg("参数不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }

        Shopping shopping=shoppingRepository.findAllByIdAndDelFlag(shoppingId,"0");

        ShopInfo shopInfo=shopInfoRepository.findAllByDelFlagAndId("0",shopId);
        if(shopInfo!=null){
            shopping.setShopName(shopInfo.getName());
            shopping.setShopId(shopInfo.getId());
        }

        HashMap<String,Shopping> hashMap=new HashMap<>();
        hashMap.put("shopping",shopping);
        apiResultBean.setData(hashMap);

        Page<ShopLibory> shopLibories=null;
        if(StringUtil.isEmpty(endTime)||StringUtil.isEmpty(startTime)){
            shopLibories=shopLiboryRepository.findAllByShopIdAndDelFlag(shopId,"0",antPage.getPageRequest());
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start = null;
            Date end = null;
            try {
                start = sdf.parse(startTime);
                end = sdf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            shopLibories=shopLiboryRepository.findAllByShopIdAndDelFlagAndCreateTimeBetween(shopId,"0",start,end,antPage.getPageRequest());


        }
        List<ShopDetailsVo> shopDetailsVos=new ArrayList<>();
        if(shopLibories.getSize()>0){
            for (ShopLibory shopLibory: shopLibories  ) {
                ShopDetailsVo shopDetailsVo=new ShopDetailsVo();
                int a=goodsGiftRepository.countshopandgoodNumandShoppingId(shopId,shopLibory.getGoodsId(),"1","0",shoppingId);
                shopDetailsVo.setGetNums(a);
                Goods goods= goodsRepository.findAllByIdAndDelFlag(shopLibory.getGoodsId(),"0");
                shopDetailsVo.setGoodsName(goods.getName());
                shopDetailsVo.setGoodsImage(goods.getImages());
                shopping.setGetNum(a);
                shopDetailsVos.add(shopDetailsVo);
            }
        }
        apiResultBean.setData(shopDetailsVos,antPage,shopLibories.getTotalElements());
        return  apiResultBean;
    }




}
